package com.vpen.server.endpoint;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 描述
 *
 * @author 韦鹏
 * @date 2022/11/25 14:25
 */
@Component
@Slf4j
@ServerEndpoint("/matter/{key}")
public class MatterServerEndpoint {

    private static final ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();


    /**
     * 发送消息
     */
    public void sendToUser(String key, String message) {
        Session session = sessionPools.get(key);
        this.sendMessage(session, message);
    }


    public void sendMessage(Session session, String message) {
        if (session == null) {
            log.error("未连接发送失败");
            return;
        }
        try {
            log.debug("服务器发送消息：{}", message);
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            log.error("发送失败");
            throw new RuntimeException(e);
        }
    }

    /**
     * 通过注解实现的的等价于WebsocketHandler里面
     * afterConnectionEstablished 等价于 @OnOpen
     * handleMessage 等价于 @OnMessage
     * afterConnectionClosed 等价于 @OnClose
     * handleTransportError 等价于 @OnError
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("key") String key) throws IOException {
        log.debug("key:{},session:{},建立连接", key, session.getId());
        sessionPools.put(key, session);
        log.debug("连接的个数：{}", sessionPools.size());
    }

    @OnClose
    public void onClose(@PathParam(value = "key") String key) throws IOException {
        log.debug("连接断开：{}", key);
        sessionPools.remove(key);
        log.debug("连接的个数：{}", sessionPools.size());
    }

    @OnMessage
    public void onMessage(String message) throws IOException {
        log.debug("收到消息：{}", message);
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        log.error("{}", throwable.getMessage());
    }

}
